<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="代码" prop="stockCode">
        <el-input
          v-model="queryParams.stockCode"
          placeholder="请输入代码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="stockName">
        <el-input
          v-model="queryParams.stockName"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="涨幅" prop="RATE">
        <el-input
          v-model="queryParams.RATE"
          placeholder="请输入涨幅"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="涨停原因" prop="limitCause">
        <el-input
          v-model="queryParams.limitCause"
          placeholder="请输入涨停原因"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['stock:day:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['stock:day:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['stock:day:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Edit"
          @click="readFile"
        >读取</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Edit"
          @click="call"
        >调用同花顺</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['stock:day:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
           type="info"
           plain
           icon="Upload"
           @click="handleImport"
           v-hasPermi="['stock:day:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dayList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键,代码+年月日" align="center" prop="recordId" />
      <el-table-column label="代码" align="center" prop="stockCode" />
      <el-table-column label="名称" align="center" prop="stockName" />
      <el-table-column label="涨幅" align="center" prop="RATE" />
      <el-table-column label="现价" align="center" prop="closePrice" />
      <el-table-column label="涨跌" align="center" prop="changePrice" />
      <el-table-column label="开盘" align="center" prop="openPrice" />
      <el-table-column label="最高" align="center" prop="HIGH" />
      <el-table-column label="最低" align="center" prop="LOW" />
      <el-table-column label="换手" align="center" prop="changeRatio" />
      <el-table-column label="首次涨停时间" align="center" prop="limitBeginTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.limitBeginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="涨停原因" align="center" prop="limitCause" />
      <el-table-column label="涨停开板次数" align="center" prop="limitOpen" />
      <el-table-column label="最终涨停时间" align="center" prop="limitEndTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.limitEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="连续涨停天数" align="center" prop="limitDays" />
      <el-table-column label="涨停封单额" align="center" prop="limitSeal" />
      <el-table-column label="涨停封成比" align="center" prop="limitRatio" />
      <el-table-column label="流通市值" align="center" prop="freeAmount" />
      <el-table-column label="所属行业" align="center" prop="CATEGORY" />
      <el-table-column label="细分行业" align="center" prop="subIndustry" />
      <el-table-column label="竞价涨幅" align="center" prop="pkRange" />
      <el-table-column label="早盘竞价量" align="center" prop="pkTurnover" />
      <el-table-column label="早盘竞价金额" align="center" prop="pkAmount" />
      <el-table-column label="早盘未匹配量" align="center" prop="pkNoTurnover" />
      <el-table-column label="早盘未匹配金额" align="center" prop="pkNoAmount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['stock:day:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['stock:day:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改每日记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dayRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="代码" prop="stockCode">
          <el-input v-model="form.stockCode" placeholder="请输入代码" />
        </el-form-item>
        <el-form-item label="名称" prop="stockName">
          <el-input v-model="form.stockName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="涨幅" prop="RATE">
          <el-input v-model="form.RATE" placeholder="请输入涨幅" />
        </el-form-item>
        <el-form-item label="现价" prop="closePrice">
          <el-input v-model="form.closePrice" placeholder="请输入现价" />
        </el-form-item>
        <el-form-item label="涨跌" prop="changePrice">
          <el-input v-model="form.changePrice" placeholder="请输入涨跌" />
        </el-form-item>
        <el-form-item label="开盘" prop="openPrice">
          <el-input v-model="form.openPrice" placeholder="请输入开盘" />
        </el-form-item>
        <el-form-item label="最高" prop="HIGH">
          <el-input v-model="form.HIGH" placeholder="请输入最高" />
        </el-form-item>
        <el-form-item label="最低" prop="LOW">
          <el-input v-model="form.LOW" placeholder="请输入最低" />
        </el-form-item>
        <el-form-item label="换手" prop="changeRatio">
          <el-input v-model="form.changeRatio" placeholder="请输入换手" />
        </el-form-item>
        <el-form-item label="首次涨停时间" prop="limitBeginTime">
          <el-date-picker clearable
            v-model="form.limitBeginTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择首次涨停时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="涨停原因" prop="limitCause">
          <el-input v-model="form.limitCause" placeholder="请输入涨停原因" />
        </el-form-item>
        <el-form-item label="涨停开板次数" prop="limitOpen">
          <el-input v-model="form.limitOpen" placeholder="请输入涨停开板次数" />
        </el-form-item>
        <el-form-item label="最终涨停时间" prop="limitEndTime">
          <el-date-picker clearable
            v-model="form.limitEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择最终涨停时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="连续涨停天数" prop="limitDays">
          <el-input v-model="form.limitDays" placeholder="请输入连续涨停天数" />
        </el-form-item>
        <el-form-item label="涨停封单额" prop="limitSeal">
          <el-input v-model="form.limitSeal" placeholder="请输入涨停封单额" />
        </el-form-item>
        <el-form-item label="涨停封成比" prop="limitRatio">
          <el-input v-model="form.limitRatio" placeholder="请输入涨停封成比" />
        </el-form-item>
        <el-form-item label="流通市值" prop="freeAmount">
          <el-input v-model="form.freeAmount" placeholder="请输入流通市值" />
        </el-form-item>
        <el-form-item label="所属行业" prop="CATEGORY">
          <el-input v-model="form.CATEGORY" placeholder="请输入所属行业" />
        </el-form-item>
        <el-form-item label="细分行业" prop="subIndustry">
          <el-input v-model="form.subIndustry" placeholder="请输入细分行业" />
        </el-form-item>
        <el-form-item label="竞价涨幅" prop="pkRange">
          <el-input v-model="form.pkRange" placeholder="请输入竞价涨幅" />
        </el-form-item>
        <el-form-item label="早盘竞价量" prop="pkTurnover">
          <el-input v-model="form.pkTurnover" placeholder="请输入早盘竞价量" />
        </el-form-item>
        <el-form-item label="早盘竞价金额" prop="pkAmount">
          <el-input v-model="form.pkAmount" placeholder="请输入早盘竞价金额" />
        </el-form-item>
        <el-form-item label="早盘未匹配量" prop="pkNoTurnover">
          <el-input v-model="form.pkNoTurnover" placeholder="请输入早盘未匹配量" />
        </el-form-item>
        <el-form-item label="早盘未匹配金额" prop="pkNoAmount">
          <el-input v-model="form.pkNoAmount" placeholder="请输入早盘未匹配金额" />
        </el-form-item>
        <el-form-item label="数据创建时间" prop="crteTime">
          <el-date-picker clearable
            v-model="form.crteTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择数据创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="数据更新时间" prop="updtTime">
          <el-date-picker clearable
            v-model="form.updtTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择数据更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

     <!-- 用户导入对话框 -->
     <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
    <el-upload
       ref="uploadRef"
       :limit="1"
       accept=".xlsx, .xls"
       :headers="upload.headers"
       :action="upload.url + '?updateSupport=' + upload.updateSupport"
       :disabled="upload.isUploading"
       :on-progress="handleFileUploadProgress"
       :on-success="handleFileSuccess"
       :auto-upload="false"
       drag
    >
       <el-icon class="el-icon--upload"><upload-filled /></el-icon>
       <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
       <template #tip>
          <div class="el-upload__tip text-center">
             <div class="el-upload__tip">
                <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
             </div>
             <span>仅允许导入xls、xlsx格式文件。</span>
             <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
       </template>
    </el-upload>
    <template #footer>
       <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
       </div>
    </template>
    </el-dialog>
  </div>
</template>

<script setup name="Day">
import { getToken } from "@/utils/auth";
import { listDay, getDay, delDay, addDay, updateDay,readPath,callThx } from "@/api/stock/day";

const { proxy } = getCurrentInstance();

const dayList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/stock/day/importData"
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    stockCode: null,
    stockName: null,
    RATE: null,
    limitCause: null,
  },
  rules: {
    stockCode: [
      { required: true, message: "代码不能为空", trigger: "blur" }
    ],
    stockName: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询每日记录列表 */
function getList() {
  loading.value = true;
  listDay(queryParams.value).then(response => {
    dayList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 读取文件 */
function readFile() {
  readPath()
}

/** 读取文件 */
function call() {
  callThx()
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "数据导入";
  upload.open = true;
};
/** 下载模板操作 */
function importTemplate() {
  proxy.download("stock/day/importTemplate", {
  }, `days_template_${new Date().getTime()}.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    stockCode: null,
    stockName: null,
    RATE: null,
    closePrice: null,
    changePrice: null,
    openPrice: null,
    HIGH: null,
    LOW: null,
    changeRatio: null,
    limitBeginTime: null,
    limitCause: null,
    limitOpen: null,
    limitEndTime: null,
    limitDays: null,
    limitSeal: null,
    limitRatio: null,
    freeAmount: null,
    CATEGORY: null,
    subIndustry: null,
    pkRange: null,
    pkTurnover: null,
    pkAmount: null,
    pkNoTurnover: null,
    pkNoAmount: null,
    crteTime: null,
    updtTime: null
  };
  proxy.resetForm("dayRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加每日记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _recordId = row.recordId || ids.value
  getDay(_recordId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改每日记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dayRef"].validate(valid => {
    if (valid) {
      if (form.value.recordId != null) {
        updateDay(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDay(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recordIds = row.recordId || ids.value;
  proxy.$modal.confirm('是否确认删除每日记录编号为"' + _recordIds + '"的数据项？').then(function() {
    return delDay(_recordIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('stock/day/export', {
    ...queryParams.value
  }, `day_${new Date().getTime()}.xlsx`)
}

getList();
</script>
